<script>
    //初始化加载
    $(function () {
        pageInit();        
    });
    //初始化页面
    function pageInit() {
        dataGridInit();
    }   
    //初始化树形表格
    function dataGridInit() {
        //从服务器端获取数据
        var url = '{{ urlfor "ResourceController.TreeGrid"}}'
        $.post(url, {}, function (re) {
            if (re.code === 0) {
                //拼接表格               
                fillTable(re.data)
            } else {
                layer.alert("数据获取失败", { icon: 2, title: '错误' })
            }
        });
    }  
    //将数据拼接到表格中 
    function fillTable(data) {
        $('#rolebox').html('');
        var html = '';
        $.each(data.treeMap, function (i, e) {
            html += '<div class="panbox">';
			html += '<label class="am-checkbox-inline"><input type="checkbox" '+ (setSelection(e.Id)?'checked':'') +' value="'+  e.Id +'" name="ids[]"> '+  e.Name +'</label>';	
			html += datafillchild(e.Id, data.treeMapChilds);
			html += '</div>';
        });

        $('#rolebox').html(html);
    }
	function datafillchild(id, fullData) {
		var html = '';
        $(fullData[id]).each(function (i, e) {
            html += '<div class="panbox-sub">';
			html += '<label class="am-checkbox-inline"><input type="checkbox" '+ (setSelection(e.Id)?'checked':'') +' value="'+  e.Id +'" name="ids[]"> '+  e.Name +'</label>';	
			if(fullData[e.Id]) {
				html += datafillchildson(e.Id, fullData);
			}
			html += '</div>';
        });
		return html;
	}
	function datafillchildson(id, fullData) {
		var html = '<div class="panbox-sub-son">';
        $(fullData[id]).each(function (i, e) {
			html += '<label class="am-checkbox-inline"><input type="checkbox" '+ (setSelection(e.Id)?'checked':'') +' value="'+  e.Id +'" name="ids[]"> '+  e.Name +'</label>';	
        });
		html += '</div>';
		return html;
	}
	//获取选择项
    function getSelections() {
        var ids = []
        $("#rolebox :checked").each(function (i, e) {
            ids.push($(e).val());
        });
        return ids;
    }    
	function setSelection(Id) {
        var check = false;
        var selectedIds='{{.selectedIds}}'
        var ids = selectedIds.split(',');      
        $.each(ids, function (i, e) {
            if (e == Id) {
                check = true;
            }
        })
        return check;
    }
</script>